package internal

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/robfig/cron/v3"
	"reflect"
	"server/app/g1/internal/model"
	"server/g"
	db1 "server/libs/db"
	"server/libs/lang"
	"server/libs/log"
	snowflake2 "server/libs/snowflake"
	"server/msg/pb"
	"strconv"
	"strings"
	"time"

	"github.com/golang-module/carbon/v2"
	"github.com/shopspring/decimal"
	"gorm.io/gorm"
)

var PledgeRate map[int64]float64

type OpenInfoResponse struct {
	OpenIssue int64  `json:"open_issue"`
	OpenTime  string `json:"open_time"`
}

func init() {
	PledgeRate = make(map[int64]float64, 5)
	PledgeRate[1] = 0.05
	PledgeRate[2] = 0.10
	PledgeRate[3] = 0.15
	PledgeRate[4] = 0.20
	PledgeRate[5] = 0.30
}

type User struct {
	Avatar        string  //头像
	Nickname      string  //昵称
	Amount        float64 //金币
	WinLoseAmount float64 //输赢金币
	UserLang      string  //语言
}

type BetItemInfo struct {
	Id    int64
	Label string
	Data  []struct {
		Id    int64
		Label string
	}
}

type Open struct {
	OpenSession     int64   //下期开奖期数
	OpenTime        string  //下期开奖时间
	OpenNumber      []int64 //上期开奖信息
	OpenNumberBack  []int64 //上期开奖备份信息
	Queue           []ItemList
	IsUnexpected    bool  //异常恢复
	OpenSessionLast int64 //
	IsLastIssue     bool  //
}

type Room struct {
	User         map[int64]*User //用户信息
	Open         *Open           //开奖信息
	BetData      []BetItemInfo   //下注数据
	Timer        *time.Timer     //定时器
	GameRoomCode string          //游戏CODE
	State        string          //状态
	Msg          []interface{}
	Channel      chan []interface{}
}
type UserPledgeInfo struct {
	Id               int64   `json:"Id"`
	Amount           float64 `json:"amount"`
	Path             string  `json:"path"`
	PledgeState      string  `json:"pledge_state"`
	PledgeLevel      int64   `json:"pledge_level"`
	PledgeAmount     float64 `json:"pledge_amount"`
	ProfitLossAmount float64 `json:"profit_loss_amount"`
}

// new对象
func NewRoom() *Room {
	var awardRecord struct {
		ID             int64  `json:"id"` // 开奖序号
		OpenIssueNum   int64  `json:"open_issue_num"`
		AwardNum       string `json:"award_num"`
		AwardStateDict int32  `json:"award_state_dict"` // 开奖状态
	}
	log.Logs().Info("====================GAME SERVER START=================")
	db1.Mysql().Table("home_award_record").Debug().Order("id desc").First(&awardRecord)

	date := carbon.Parse(carbon.Now().ToDateString())
	a1, _ := strconv.ParseInt(date.Format("Ymd")+"001", 10, 64)
	var isunexpected bool
	if awardRecord.AwardStateDict == OPEN_AWARD_PENDING {
		awardRecord.OpenIssueNum = awardRecord.OpenIssueNum
		isunexpected = true
		db1.Mysql().Table("home_award_record").Debug().Where("id =?", awardRecord.ID).Delete("")
	} else {
		awardRecord.OpenIssueNum += 1
		if a1 > awardRecord.OpenIssueNum {
			awardRecord.OpenIssueNum = a1
		}
		isunexpected = false
	}

	datetime := carbon.Parse(carbon.Now().ToDateTimeString())
	ok := datetime.StartOfHour().DiffAbsInMinutes(datetime)
	m := ok/5*5 + 5
	//m := ok/3*3 + 3
	dd := datetime.StartOfHour().AddMinutes(int(m)).ToDateTimeString()
	num := []int64{}
	json.Unmarshal([]byte(awardRecord.AwardNum), &num)
	room := &Room{
		User: map[int64]*User{},
		Open: &Open{
			OpenSession:    awardRecord.OpenIssueNum,
			OpenNumber:     num,
			OpenTime:       dd,
			OpenNumberBack: num,
			IsUnexpected:   isunexpected,
		},
		Timer:        time.NewTimer(time.Second),
		State:        "StartResponse",
		GameRoomCode: "1",
		Channel:      make(chan []interface{}, 1),
	}
	db1.Mysql().Table("home_config").Debug().
		Where("config_key = ?", "open_issue").
		Updates(map[string]interface{}{
			"config_value": awardRecord.OpenIssueNum,
			"updated_at":   time.Now(),
		})
	log.Logs().Info("OpenSession: ", awardRecord.OpenIssueNum, "   OpenTime:", dd)
	var openinfo OpenInfoResponse
	openinfo.OpenTime = dd
	openinfo.OpenIssue = awardRecord.OpenIssueNum
	OpeninfoRaw, err := json.Marshal(openinfo)
	if err != nil {
		openinfo.OpenTime = ""
		openinfo.OpenIssue = 0
	}
	payload := string(OpeninfoRaw)
	ctx := context.Background()
	db1.Redis().Set(ctx, "OPEN_INFO", payload, 0)

	room.Run()
	return room
}

func (t *Room) Run() {
	go func() {
		for {
			select {
			case args := <-t.Channel:
				f := strings.TrimPrefix(reflect.TypeOf(args[1]).String(), "*pb.G1")
				value := reflect.ValueOf(t)
				t.Msg = args
				value.MethodByName(f).Call([]reflect.Value{})
			}
		}
	}()
	go func() {
		t.StaticsReadyNEXT()
		t.Timer.Reset(time.Second * 3)
		<-t.Timer.C
		for {
			//开始游戏
			t.State = "StartResponse"
			t.StartResponse()

			//开始下注
			t.State = "StartBetResponse"
			t.StartBetResponse()

			//停止下注
			c := cron.New()
			c.AddFunc("*/5 * * * *", func() {
				fmt.Println("=========>", "时间到:", time.Now())
				t.Timer.Reset(time.Second * 0)
				c.Stop()
			})
			fmt.Println("=========>倒计时开始: ", time.Now())
			c.Start()
			<-t.Timer.C
			t.State = "StopBetResponse"
			t.StopBetResponse()

			//动画
			t.State = "AnimationResponse"
			t.AnimationResponse()
			t.NextResponse()

			//开奖
			t.Timer.Reset(time.Second * 47)
			<-t.Timer.C
			t.State = "OpenResponse"
			//开奖信息返回
			t.OpenResponse()

			//游戏结束
			t.Timer.Reset(time.Second * 1)
			<-t.Timer.C
			t.State = "StopResponse"
			t.StopResponse()
		}
	}()
}

func (t *Room) locked() int {
	lockKey := "my_lock"
	lockValue := "locked"
	lockExpire := 30 // 锁的过期时间，单位为秒

	luaScript := `local lockKey = KEYS[1]
		local lockValue = ARGV[1]
		local lockExpire = ARGV[2]
		if redis.call('SETNX', lockKey, lockValue) == 1 then
			return redis.call('EXPIRE', lockKey, lockExpire)
		else
			return 0
		end`

	lua, err := db1.Redis().Eval(context.Background(), luaScript, []string{lockKey}, lockValue, lockExpire).Result()
	fmt.Println("执行lua脚本的结果：", int(lua.(int64)))
	if err != nil {
		return 0
	} else {
		return int(lua.(int64))
	}
}

// 登录游戏
func (t *Room) LoginRequest() {
	userId := t.Msg[0].(int64)
	langinfo := t.Msg[1].(*pb.G1LoginRequest).GetLang()
	langinfo = lang.GetValidLang(langinfo)
	if _, ok := t.User[userId]; !ok {
		t.User[userId] = &User{}
		t.User[userId].UserLang = langinfo
	}

	g.GameRpc.Go("UpdateGameCode", userId, t.GameRoomCode)
	g.Send([]int64{userId}, t.GameRoomCode, &pb.G1LoginRequest{})
	if t.State == "AnimationResponse" || t.State == "OpenResponse" || t.State == "StopResponse" {
		//g.Send([]int64{userId}, t.GameRoomCode, &pb.G1RoomInfoResponse{
		//	State: t.State,
		//})
		g.Send([]int64{userId}, t.GameRoomCode, &pb.G1RoomInfoResponse{
			OpenSession: t.Open.OpenSession,
			OpenTime:    t.Open.OpenTime,
			OpenNumber:  t.Open.OpenNumberBack,
			BetData:     NewGenerate().GetBetData(langinfo).BetData,
			State:       t.State,
		})
	} else {
		g.Send([]int64{userId}, t.GameRoomCode, &pb.G1RoomInfoResponse{
			OpenSession: t.Open.OpenSession,
			OpenTime:    t.Open.OpenTime,
			OpenNumber:  t.Open.OpenNumber,
			BetData:     NewGenerate().GetBetData(langinfo).BetData,
			State:       t.State,
		})
	}
}

// 下注请求
func (t *Room) BetRequest() {

}

func (t *Room) StartResponse() {
	g.Send(g.Keys(t.User), t.GameRoomCode, &pb.G1StartResponse{})
}

func (t *Room) StartBetResponse() {
	g.Send(g.Keys(t.User), t.GameRoomCode, &pb.G1StartBetResponse{})
}

func (t *Room) StopBetResponse() {
	g.Send(g.Keys(t.User), t.GameRoomCode, &pb.G1StopBetResponse{})
}

func (t *Room) AnimationResponse() {
	OpenSession := t.Open.OpenSession
	date := carbon.Parse(carbon.Now().ToDateString())
	a1, _ := strconv.ParseInt(date.Format("Ymd")+"001", 10, 64)
	if a1 >= t.Open.OpenSession {
		if t.Open.OpenSession == a1 {
			a1 = a1 + 1
		}
		db1.Mysql().Table("home_config").Debug().Where("config_key = ?", "open_issue").Update("config_value", a1)
		t.Open.OpenSession = a1
	} else {
		t.Open.OpenSession += 1
		a3, _ := strconv.ParseInt(carbon.Parse(carbon.Now().AddMinutes(5).ToDateString()).Format("Ymd")+"001", 10, 64)
		if a3 > t.Open.OpenSession {
			t.Open.IsLastIssue = true
			t.Open.OpenSessionLast = t.Open.OpenSession
			t.Open.OpenSession = a3
		}
		db1.Mysql().Table("home_config").Debug().
			Where("config_key = ?", "open_issue").
			Updates(map[string]interface{}{
				"config_value": strconv.FormatInt(t.Open.OpenSession, 10),
				"updated_at":   time.Now(),
			})
	}

	datetime := carbon.Parse(carbon.Now().ToDateTimeString())
	ok := datetime.StartOfHour().DiffAbsInMinutes(datetime)
	m := ok/5*5 + 5
	//m := ok/3*3 + 3
	dd := datetime.StartOfHour().AddMinutes(int(m)).ToDateTimeString()
	t.Open.OpenNumberBack = t.Open.OpenNumber
	t.Open.OpenTime = dd
	//t.Open.OpenNumber = new(Generate).Open()
	if !t.Open.IsUnexpected {
		OpenSession = t.Open.OpenSession - 1
		if t.Open.IsLastIssue {
			OpenSession = t.Open.OpenSessionLast - 1
			t.Open.IsLastIssue = false
		}
	}
	log.Logs().Info("--------->控制输赢开始,当前时间: ", time.Now().String(), "<---------------")
	t.Open.OpenNumber = GEN_HORSE_Control(OpenSession)
	log.Logs().Info("--------->控制输赢结束,当前时间: ", time.Now().String(), "开将开奖期号:", t.Open.OpenNumber, "<---------------")
	//t.Open.OpenNumber = new(Generate).Open()
	//t.Open.OpenNumber = []int64{10, 3, 6, 4, 1, 8, 7, 9, 2, 5}
	fmt.Println(t.Open.OpenNumber)
	n, _ := json.Marshal(t.Open.OpenNumber)
	db1.Mysql().Table("home_award_record").Create(&map[string]any{
		"id":               snowflake2.GetIdInt64(),
		"open_issue_num":   OpenSession,
		"award_num":        string(n),
		"award_state_dict": OPEN_AWARD_PENDING,
		"created_at":       time.Now(),
		"updated_at":       time.Now(),
	})
	fmt.Println("新开奖信息入库-", "开奖期号: ", OpenSession, "开奖号码: ", string(n))
	log.Logs().Info("新开奖信息入库-", "开奖期号: ", OpenSession, "开奖号码: ", string(n))
	Animated_Data := HorseRand_Yuan(t.Open.OpenNumber)
	t.Open.Queue = Animated_Data
	animationResponse := pb.G1AnimationResponse{}
	animationResponse.StartTime = carbon.Now().Timestamp()
	for k, _ := range t.Open.Queue {
		animationResponse.Queue = append(animationResponse.Queue, &pb.G1AnimationResponse_QueueItem{})
		animationResponse.Queue[k].Data = []*pb.G1AnimationResponse_QueueItem_QueueSubItem{}
		for k1, _ := range t.Open.Queue[k].items {
			animationResponse.Queue[k].Data = append(animationResponse.Queue[k].Data,
				&pb.G1AnimationResponse_QueueItem_QueueSubItem{T: t.Open.Queue[k].items[k1].t, S: t.Open.Queue[k].items[k1].s})
		}
	}
	animationResponse.OpenNumber = t.Open.OpenNumber
	g.Send(g.Keys(t.User), t.GameRoomCode, &animationResponse)
	t.Open.IsUnexpected = false
	var openinfo OpenInfoResponse
	openinfo.OpenTime = t.Open.OpenTime
	openinfo.OpenIssue = t.Open.OpenSession
	OpeninfoRaw, err := json.Marshal(openinfo)
	if err != nil {
		openinfo.OpenTime = ""
		openinfo.OpenIssue = 0
	}
	payload := string(OpeninfoRaw)
	ctx := context.Background()
	db1.Redis().Set(ctx, "OPEN_INFO", payload, 0)
}

func (t *Room) NextResponse() {
	nextResponse := pb.G1NextOpenResponse{}
	nextResponse.OpenTime = t.Open.OpenTime
	nextResponse.OpenSession = t.Open.OpenSession
	g.Send(g.Keys(t.User), t.GameRoomCode, &nextResponse)
	t.StaticsReadyNEXT()
}

func (t *Room) OpenResponse() {
	openResponse := pb.G1OpenResponse{}
	openResponse.OpenTime = t.Open.OpenTime
	openResponse.OpenSession = t.Open.OpenSession
	openResponse.OpenNumber = t.Open.OpenNumber
	g.Send(g.Keys(t.User), t.GameRoomCode, &openResponse)
}

func (t *Room) StopResponse() {
	// m := NewGenerate().GetAwardData(t.Open.OpenNumber)

	var awardRecord struct {
		Id           int64  `json:"Id"`
		OpenIssueNum int64  `json:"open_issue_num"`
		AwardNum     string `json:"award_num"`
	}

	var order []struct {
		Id             int64     `json:"id"`
		UserId         int64     `json:"user_id"`
		Code           string    `json:"code"`
		Amount         float64   `json:"amount"`                                         // 金额
		TrackNum       int32     `gorm:"column:track_num; json:"track_num"`              // 赛道号码
		BetNum         int32     `gorm:"column:bet_num;json:"bet_num"`                   // 投注号码
		SingleEvenDict int32     `gorm:"column:single_even_dict;json:"single_even_dict"` // 号码单双
		BigSmallDict   int32     `gorm:"column:big_small_dict;json:"big_small_dict"`     // 号码大小
		AwardNum       float64   `json:"award_num"`
		CreatedAt      time.Time `json:"created_at"` // 创建时间
		User           struct {
			Id            int64   `json:"Id"`
			Amount        float64 `json:"amount"`
			AccountStatus int32   `json:"account_status"`
		} `gorm:"foreignKey:id;references:user_id"  json:"user"`
		OpenAward []struct {
			OrderId    int64   `json:"order_id"`    //订单ID
			BetDetail  string  `json:"bet_detail"`  //下注详情
			ItemAmount float64 `json:"item_amount"` //金额
			AwardNum   float64 `json:"award_num"`   //奖金数目
		} `gorm:"foreignKey:order_id;references:Id"  json:"open_award"`
		BetRecordStruct map[string]*struct {
			BetAmount   float64 `json:"bet_amount"`
			AwardAmount float64 `json:"award_amount"`
		} `gorm:"-" json:"bet_record_struct"`
	}
	db1.Mysql().Table("home_award_record").Order("id desc").First(&awardRecord)
	db1.Mysql().Table("home_award_record").Debug().
		Where("id = ?", awardRecord.Id).
		Updates(map[string]interface{}{
			"award_state_dict": OPEN_AWARD_FINISH,
		})
	go func() {
		AwardList_Cache()
	}()
	num := []int64{}
	json.Unmarshal([]byte(awardRecord.AwardNum), &num)
	m := NewGenerate().GetAwardData(num)
	db1.Mysql().Debug().Table("home_order").
		Preload("User", func(db *gorm.DB) *gorm.DB {
			return db.Table("home_user_info").
				Select("id,amount,account_status")
		}).
		//Preload("OpenAward", func(db *gorm.DB) *gorm.DB {
		//	return db.Table("home_detail_record").
		//		Select("order_id,bet_detail,item_amount,award_num")
		//}).
		Where("issue_num = ?", awardRecord.OpenIssueNum).
		Where("order_state_dict = ?", BET_PROGRESS).
		FindInBatches(&order, 1000, func(tx *gorm.DB, batch int) error {
			for k, _ := range order {
				//for k1, value := range order[k].OpenAward {
				//	a := decimal.NewFromFloat(m[value.BetDetail])
				//	b := decimal.NewFromFloat(order[k].User.FixedOdds)
				//	c := decimal.NewFromFloat(order[k].OpenAward[k1].ItemAmount)
				//	order[k].OpenAward[k1].AwardNum, _ = a.Mul(b).Mul(c).RoundFloor(2).Float64()
				//}
				BetDetail := RestoreBetDetail(order[k].TrackNum, order[k].BetNum, order[k].BigSmallDict, order[k].SingleEvenDict)
				a := decimal.NewFromFloat(m[BetDetail])
				c := decimal.NewFromFloat(order[k].Amount)
				d := decimal.NewFromFloat(order[k].Amount)
				order[k].AwardNum, _ = a.Mul(c).Sub(d).RoundFloor(2).Float64()
			}
			//for k, _ := range order {
			//	for k1, _ := range order[k].OpenAward {
			//		a := decimal.NewFromFloat(order[k].AwardNum)
			//		b := decimal.NewFromFloat(order[k].OpenAward[k1].ItemAmount)
			//		order[k].AwardNum, _ = a.Sub(b).RoundFloor(2).Float64()
			//		if order[k].OpenAward[k1].AwardNum > 0 {
			//			db1.Mysql().Debug().Table("home_detail_record").
			//				Where("order_id = ?", order[k].Id).
			//				Where("user_id = ?", order[k].UserId).
			//				Where("bet_detail =? ", order[k].OpenAward[k1].BetDetail).
			//				Updates(map[string]interface{}{
			//					"award_num":  order[k].OpenAward[k1].AwardNum,
			//					"updated_at": time.Now(),
			//				})
			//		}
			//	}
			//}

			for k, _ := range order {
				txInternal := db1.Mysql().Begin()
				txInternal.Table("home_order").
					Where("id = ?", order[k].Id).
					Updates(map[string]interface{}{
						//"state":     "success",
						//"sub_state": "award",
						"order_state_dict": BET_FINISHED,
						"award_num":        order[k].AwardNum,
					})
				if order[k].AwardNum > ZERO_VALUE && order[k].User.AccountStatus == NORMAL_USER_STATE {
					tmpAwardAmount := decimal.NewFromFloat(order[k].AwardNum).Add(decimal.NewFromFloat(order[k].Amount))
					tmpAwardAmountValue, _ := tmpAwardAmount.Float64()
					var userCurrentAmount float64
					db1.Mysql().Debug().Table("home_user_info").
						Select("amount").
						Where("id = ?", order[k].UserId).
						Find(&userCurrentAmount)

					txInternal.Table("home_user_info").
						Where("id = ?", order[k].UserId).
						Update("amount", gorm.Expr("amount + ?", tmpAwardAmountValue))

					afterAmount, _ := decimal.NewFromFloat(userCurrentAmount).Add(tmpAwardAmount).Float64()
					txInternal.Table("home_user_change").Create(&map[string]any{
						"id":               snowflake2.GetIdInt64(),
						"before_amount":    userCurrentAmount,
						"current_amount":   tmpAwardAmountValue,
						"after_amount":     afterAmount,
						"user_id":          order[k].UserId,
						"key_id":           snowflake2.GetIdInt64(),
						"stream_type_dict": WIN_LOSE,
						"created_at":       time.Now(),
						"updated_at":       time.Now(),
					})

					if _, ok := t.User[order[k].UserId]; ok {
						SumValue, _ := decimal.NewFromFloat(t.User[order[k].UserId].WinLoseAmount).
							Add(decimal.NewFromFloat(order[k].AwardNum)).Float64()
						t.User[order[k].UserId].Amount = afterAmount
						t.User[order[k].UserId].WinLoseAmount = SumValue
					}
				}
				var PledgeMap map[int64][]model.HomePledgeModel
				PledgeMap = make(map[int64][]model.HomePledgeModel)
				GetPledgeInfoAll(order[k].UserId, PledgeMap)

				if len(PledgeMap) == ZERO_VALUE {
					continue
				} else {
					ProfitLossDecimal := decimal.NewFromFloat(order[k].AwardNum).Neg()
					PledgeInfoList, _ := PledgeMap[order[k].UserId]
					var MaxDividendRate float64
					MaxDividendRate = ZERO_VALUE
					for _, value := range PledgeInfoList {
						if order[k].CreatedAt.Before(value.CreatedAt) {
							continue
						}
						if value.ID == ZERO_VALUE || value.UserID == order[k].UserId {
							if value.ID == order[k].UserId {
								MaxDividendRate = ZERO_VALUE
							}
							continue
						}
						if value.PledgeStateDict != PLEDGE_NORMAL {
							continue
						}
						var state int32
						state = value.PledgeStateDict
						GradeDifferenceRate, _ := decimal.NewFromFloat(value.DividendRate).Sub(decimal.NewFromFloat(MaxDividendRate)).Float64()
						if GradeDifferenceRate <= ZERO_VALUE {
							continue
						}
						MaxDividendRate = value.DividendRate
						FinalValue, _ := ProfitLossDecimal.Mul(decimal.NewFromFloat(GradeDifferenceRate)).Float64()
						var totalDividendAmount float64
						txInternal.Debug().Table("home_pledge").
							Select("total_dividend_amount").
							Where("id = ?", value.ID).
							Find(&totalDividendAmount)
						AfterValue, _ := decimal.NewFromFloat(FinalValue).Add(decimal.NewFromFloat(totalDividendAmount)).Float64()
						HalfPledgeAmountDecimal := decimal.NewFromFloat(value.PledgeAmount).Div(decimal.NewFromInt(2))
						DetermineValue, _ := HalfPledgeAmountDecimal.Add(decimal.NewFromFloat(AfterValue)).Float64()
						var ForceClear bool
						ForceClear = false
						if DetermineValue < 0 {
							state = PLEDGE_ABORT
							TotalAmount, _ := decimal.NewFromFloat(value.PledgeAmount).Add(decimal.NewFromFloat(AfterValue)).Float64()
							if TotalAmount < 0 {
								ForceClear = true
								var TopUserAmount float64
								db1.Mysql().Debug().Table("home_user_info").
									Select("amount").
									Where("id = ?", value.UserID).
									Find(&TopUserAmount)

								DeductionAmount, _ := decimal.NewFromFloat(TopUserAmount).Add(decimal.NewFromFloat(TotalAmount)).Float64()
								txInternal.Debug().Table("home_user_info").
									Where("id = ?", value.UserID).
									Updates(map[string]interface{}{
										"amount": DeductionAmount,
									})
								txInternal.Debug().Table("home_pledge").
									Where("id = ?", value.ID).
									Updates(map[string]interface{}{
										"pledge_amount":         TotalAmount,
										"total_dividend_amount": AfterValue,
										"day_dividend_amount":   AfterValue,
										"pledge_state_dict":     state,
									})
								BeforeActualAmount, _ := decimal.NewFromFloat(TopUserAmount).
									Add(decimal.NewFromFloat(value.PledgeAmount)).Float64()
								txInternal.Debug().Table("home_user_change").Create(&[]map[string]interface{}{
									{
										"id":               snowflake2.GetIdInt64(),
										"before_amount":    BeforeActualAmount,
										"current_amount":   AfterValue,
										"after_amount":     DeductionAmount,
										"user_id":          value.UserID,
										"key_id":           snowflake2.GetIdInt64(),
										"stream_type_dict": FORCE,
										"created_at":       time.Now(),
										"updated_at":       time.Now(),
									},
									{
										"id":               snowflake2.GetIdInt64(),
										"before_amount":    TopUserAmount,
										"current_amount":   TotalAmount,
										"after_amount":     DeductionAmount,
										"user_id":          value.UserID,
										"key_id":           snowflake2.GetIdInt64(),
										"stream_type_dict": FORCE_CHANGE,
										"created_at":       time.Now(),
										"updated_at":       time.Now(),
									},
								})
							}
						}
						if ForceClear == false {
							txInternal.Debug().Table("home_pledge").
								Where("id = ?", value.ID).
								Updates(map[string]interface{}{
									"total_dividend_amount": gorm.Expr("total_dividend_amount + ?", FinalValue),
									"day_dividend_amount":   gorm.Expr("day_dividend_amount + ?", FinalValue),
								})
							txInternal.Debug().Table("home_user_change").Create(&map[string]any{
								"id":               snowflake2.GetIdInt64(),
								"before_amount":    totalDividendAmount,
								"current_amount":   FinalValue,
								"after_amount":     AfterValue,
								"user_id":          value.UserID,
								"key_id":           snowflake2.GetIdInt64(),
								"stream_type_dict": DIVIDEND,
								"created_at":       time.Now(),
								"updated_at":       time.Now(),
							})

						}
					}
				}
				txInternal.Commit()
			}
			return nil
		})
	for k, v := range t.User {
		var userCurrentAmount float64
		userCurrentAmount = ZERO_VALUE
		db1.Mysql().Table("home_user_info").
			Select("amount").
			Where("id = ?", k).
			Find(&userCurrentAmount)
		t.User[k].Amount = userCurrentAmount
		g.Send([]int64{k}, t.GameRoomCode, &pb.G1StopResponse{
			WinLoseAmount: v.WinLoseAmount,
			Amount:        v.Amount,
		})
		t.User[k].WinLoseAmount = ZERO_VALUE
	}
	log.Logs().Info("====本期开奖结束,期号: ", awardRecord.OpenIssueNum, "  开奖号码: ", awardRecord.AwardNum, "=====")
}

func (t *Room) StaticsReadyNEXT() {
	Openn_Issue := strconv.FormatInt(t.Open.OpenSession, 10)
	ctx_init := context.Background()
	dataGetvalue := db1.Redis().HExists(ctx_init, Openn_Issue, "1")
	if dataGetvalue.Val() {
		fmt.Println(dataGetvalue.Val())
		return
	}
	betlist_result := make([]float64, 10)
	var data, _ = json.Marshal(betlist_result)
	for i := 1; i <= 10; i++ {
		db1.Redis().HSet(ctx_init, Openn_Issue, fmt.Sprintf("%d", i), data)
	}
	for i := 3; i <= 19; i++ {
		db1.Redis().HSet(ctx_init, Openn_Issue, fmt.Sprintf("sum-%d", i), data)
	}
	db1.Redis().Expire(ctx_init, Openn_Issue, 5*time.Hour)
}
